package ay.shadow.seckill.rabbitmq;

import ay.shadow.seckill.entity.SeckillMessage;
import ay.shadow.seckill.entity.SeckillOrder;
import ay.shadow.seckill.entity.User;
import ay.shadow.seckill.service.IGoodsService;
import ay.shadow.seckill.service.IOrderService;
import ay.shadow.core.utils.JsonUtils;
import ay.shadow.seckill.entity.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReceiver {

    //@RabbitListener(queues = "queue")
    //public void receive(Object msg){
    //    log.info("接收的消息: {}",msg);
    //}

    //@RabbitListener(queues = "QUEUE01")
    //public void receive01(Object msg){
    //    log.info("QUEUE01:{}",msg);
    //}

    //@RabbitListener(queues = "QUEUE02")
    //public void receive02(Object msg){
    //    log.info("QUEUE02:{}",msg);
    //}


    //@RabbitListener(queues = "queue_direct01")
    //public void receive03(Object msg){
    //    log.info("queue_direct01:{}",msg);
    //}
    //
    //@RabbitListener(queues = "queue_direct02")
    //public void receive04(Object msg){
    //    log.info("queue_direct02:{}",msg);
    //}
    //
    //@RabbitListener(queues = "queue_topic01")
    //public void receive05(Object msg){
    //    log.info("topic_queue01:{}",msg);
    //}
    //
    //@RabbitListener(queues = "queue_topic02")
    //public void receive06(Object msg){
    //    log.info("topic_queue02:{}",msg);
    //}

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;

    /**
     * @Param
     * @Description 下单操作
     * @Return
     */
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message) {
        log.info("接收的消息:{}", message);
        SeckillMessage seckillMessage = JsonUtils.jsonStr2Object(message, SeckillMessage.class);
        User user = seckillMessage.getUser();
        Long goodsId = seckillMessage.getGoodsId();
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        if (goodsVo.getStockCount() < 1) {
            return;
        }
        // 判断是否重复抢购
        SeckillOrder seckillOrder =
                (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if (seckillOrder != null) {
            return;
        }
        // 下单
        orderService.seckill(user,goodsVo);

    }
}
